package com.hxkcloud.patient.aerotel.util;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基于android通用功能的工具类(F = Function)
 *
 * @author AlexHuang
 * @email huangyu407@qq.com
 */
public class F {

//    public static byte[] getFileData(String filePath) {
//        FileInputStream fis = null;
//        ByteArrayOutputStream bos = null;
//        try {
//            File file = new File(filePath);
//            fis = new FileInputStream(file);
//            bos = new ByteArrayOutputStream();
//            byte[] b = new byte[(int) file.length()];
//            int n;
//            while ((n = fis.read(b)) != -1) {
//                bos.write(b, 0, n);
//            }
//            return bos.toByteArray();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            InternalUtils.close(fis);
//            InternalUtils.close(bos);
//        }
//        return null;
//    }


//    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
//                                   double newHeight) {
//        // 获取这个图片的宽和高
//        BitmapFactory.Options o = new BitmapFactory.Options();
//        o.inJustDecodeBounds = true;
//        BitmapFactory.decodeStream(new FileInputStream(bgimage), null, o);
//
//        float width = bgimage.getWidth();
//        float height = bgimage.getHeight();
//        // 创建操作图片用的matrix对象
//        Matrix matrix = new Matrix();
//        // 计算宽高缩放率
//        float scaleWidth = ((float) newWidth) / width;
//        float scaleHeight = ((float) newHeight) / height;
//        float scale = scaleWidth > scaleHeight? scaleWidth:scaleHeight;
//        // 缩放图片动作
//        matrix.postScale(scale, scale);
//        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
//                (int) height, matrix, true);
//        return bitmap;
//    }


//    private Bitmap decodeFile(File f) {
//        try {
//            // decode image size
//
//
//
//            // Find the correct scale value. It should be the power of 2.
//            final int REQUIRED_SIZE = 1280;
//            int width_tmp = o.outWidth, height_tmp = o.outHeight;
//            int scale = 1;
//            while (true) {
//                if (width_tmp / 2 < REQUIRED_SIZE
//                        || height_tmp / 2 < REQUIRED_SIZE)
//                    break;
//                width_tmp /= 2;
//                height_tmp /= 2;
//                scale *= 2;
//            }
//
//            // decode with inSampleSize
//            o.inJustDecodeBounds = false;
//            o.inSampleSize = scale;
//
//            return BitmapFactory.decodeStream(new FileInputStream(f), null, o);
//        } catch (FileNotFoundException e) {
//        }
//        return null;
//    }
    /**
     * 按照比例压缩图片
     * @param filePath
     * @return
     */
    public static Bitmap getFileBitmap(String filePath) {
        Log.e("FILE SIZE ",new File(filePath).length()+"");
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath,o);
        final int REQUIRED_SIZE = 1280;
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        if (width_tmp<=1280&&height_tmp<=1280){//都小于1280
            o.inJustDecodeBounds = false;
            o.inSampleSize = scale;
            Log.e("SCALE","with = "+width_tmp+"height ="+height_tmp+"都小于1280");
            return BitmapFactory.decodeFile(filePath, o);
        }else if((width_tmp>1280&&height_tmp<=1280)||(width_tmp<=1280&&height_tmp<1280)){//宽高只有一个大于1280
            if (width_tmp/height_tmp>2){//不变
                o.inJustDecodeBounds = false;
                o.inSampleSize = scale;
                Log.e("SCALE","with = "+width_tmp+"height ="+height_tmp+"一个小于1280  比例大于2");
                return BitmapFactory.decodeFile(filePath, o);
            }else {
                o.inJustDecodeBounds = false;
                scale = width_tmp>height_tmp?width_tmp/REQUIRED_SIZE:height_tmp/REQUIRED_SIZE;
                Log.e("SCALE","with = "+width_tmp+"height ="+height_tmp+"一个小于1280  比例小于2"+"缩放"+scale);
                o.inSampleSize = scale;
                return BitmapFactory.decodeFile(filePath, o);
            }
        }else if(width_tmp>1280&&height_tmp>1280){
            o.inJustDecodeBounds = false;
            scale = width_tmp<height_tmp?width_tmp/REQUIRED_SIZE:height_tmp/REQUIRED_SIZE;
            Log.e("SCALE","with = "+width_tmp+"height ="+height_tmp+"都大于1280  比例小于2"+"缩放"+scale);
            o.inSampleSize = scale;
            return BitmapFactory.decodeFile(filePath, o);
        }
        o.inJustDecodeBounds = false;
        o.inSampleSize = scale;
        Log.e("SCALE","with = "+width_tmp+"height ="+height_tmp+"都大于1280  比例小于2"+"缩放"+scale+"未压缩");
        return BitmapFactory.decodeFile(filePath, o);
    }

    /**
     * 旋转压缩图片
     * @param filePath
     * @return
     */
    public static Bitmap getFileBitmapRote(String filePath) {
        int degree = readPictureDegree(filePath);
        Bitmap cameraBitmap = getFileBitmap(filePath);
        Bitmap bitmap = rotaingImageView(degree, cameraBitmap);
        return bitmap;
    }




    public static void comPressBitmapByParam(Picture picture, Bitmap bitmap) {
        File f = new File(picture.getZoomPath());
        Log.e("FILE SIZE ZoomPath",f.length()+"");
        if (f.exists()) {//使用时间保证路径的唯一性。如果存在就不用再次存储
           return;
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.e("FILE SIZE ZoomPath",f.length()+"");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 旋转压缩图片
     * @param picture
     * @return
     */
    public static Bitmap getBitmapByParam(Picture picture) {
       return picture.isTakephoto()?F.getFileBitmapRote(picture.getPath()):F.getFileBitmap(picture.getPath());
    }


    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /** 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();;
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }


    public static BitmapFactory.Options getBitmapOption (int inSampleSize){

        System.gc();
        BitmapFactory.Options options =new BitmapFactory.Options();
        options.inPurgeable=true;
        options.inSampleSize= inSampleSize;
        return options;
    }

    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    /**
     * 短震动
     *
     * @param context
     */
    public static void makeShortVibrator(Context context) {
        Vibrator vibrator = (Vibrator) context
                .getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(5);
    }

    /**
     * 长震动
     *
     * @param context
     */
    public static void makeLongVibrator(Context context) {
        Vibrator vibrator = (Vibrator) context
                .getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(100);
    }

    /**
     * 显示软键盘
     *
     * @param context
     * @param target
     */
    public static void showSoftInput(Context context, View target) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(target, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 隐藏软键盘
     *
     * @param context
     * @param target
     */
    public static void hideSoftInput(Context context, View target) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(target.getApplicationWindowToken(), 0);
    }

    /**
     * 判断activity是否最顶端（正在显示中）
     *
     * @param context
     * @param activityClass
     * @return
     */
    public static boolean isTopActivity(Context context, Class<?> activityClass) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(activityClass.getName())) {
            return true;
        }
        return false;
    }

    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * 添加联系人
     *
     * @param context
     * @param name
     * @param phoneNum
     */
    public static long addContact(Context context, String name, String phoneNum) {
        ContentValues values = new ContentValues();
        Uri rawContactUri = context.getContentResolver().insert(
                RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        // 向data表插入数据
        if (name != "") {
            values.clear();
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
            values.put(StructuredName.GIVEN_NAME, name);
            context.getContentResolver().insert(
                    ContactsContract.Data.CONTENT_URI, values);
        }

        // 向data表插入电话号码
        if (phoneNum != "") {
            values.clear();
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
            values.put(Phone.NUMBER, phoneNum);
            values.put(Phone.TYPE, Phone.TYPE_MOBILE);
            context.getContentResolver().insert(
                    ContactsContract.Data.CONTENT_URI, values);
        }

        return rawContactId;
    }


    /**
     * 获取库Phon表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    /**
     /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;

    /**
     * 得到手机通讯录联系人信息
     **/
    public static Map<String, List<?>> getPhoneContacts(Context context) {
        Map<String, List<?>> phoneContacts = new HashMap<>();
        /**
         * 联系人名称
         **/
        ArrayList<String> mContactsName = new ArrayList<>();

        /**
         * 联系人号码
         **/
        ArrayList<String> mContactsNumber = new ArrayList<>();


        ContentResolver resolver = context.getContentResolver();

        // 获取手机联系人
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);

        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                //得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                //当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;

                //得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                mContactsName.add(contactName);
                mContactsNumber.add(phoneNumber);
            }
            phoneContacts.put("number", mContactsNumber);
            phoneContacts.put("name",mContactsName);
            phoneCursor.close();
        }
        return phoneContacts;
    }

    /**
     * 删除联系人
     *
     * @param context
     * @param rawContactId
     */
    public static void deleteContact(Context context, long rawContactId) {
        context.getContentResolver().delete(
                ContentUris.withAppendedId(RawContacts.CONTENT_URI,
                        rawContactId), null, null);
    }

    /**
     * 显示Notification
     *
     * @param context
     * @param icon
     * @param title
     * @param content
     * @param contentIntent
     */
    public static void showNotification(Context context, int icon,
                                        String title, String content, PendingIntent contentIntent) {
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification.Builder(context)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(icon)
                .setContentIntent(contentIntent)
                .getNotification();

        // 添加声音
        notification.defaults |= Notification.DEFAULT_SOUND;
        // 或者
        // notification.sound =
        // Uri.parse("file:///sdcard/notification/ringer.mp3");
        // notification.sound =
        // Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

        // LED提醒模式:
        notification.ledARGB = 0xff00ff00;
        notification.ledOnMS = 300; // 亮的时间
        notification.ledOffMS = 1000; // 灭的时间
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;

        // 在通知栏上点击此通知后自动清除此通知
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // 添加震动
        long[] vibreate = new long[]{1000, 1000};
        notification.vibrate = vibreate;

//        mNotificationManager.notify(Integer.valueOf(IDUtils.randomNumber(5)), notification);
    }




    /**
     * dip转化成px
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 设置本地头像的缓存
     *
     * @param mContext
     * @param iv_userAvatar
     */
//    public static void setCacheAvatar(Context mContext, CircleImageView iv_userAvatar, File avatarImageFile) {
//        Bitmap bitmap = BitmapFactory.decodeFile(avatarImageFile.getAbsolutePath());
//        iv_userAvatar.setImageBitmap(bitmap);
//    }
    /**
     * px转化成dip
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * px转化成sp
     */
    public static int px2sp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * sp转化成px
     */
    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * scale + 0.5f);
    }
}
